package hxg.tcptest.demo4;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author HeXiangGuang
 * @create 2021-06-30 22:22
 * 用户注册客户端
 */
public class UserClient {
    public static void main(String[] args) throws Exception{
        System.out.println("------请选择1注册2登录------");
        Scanner input = new Scanner(System.in);
        int choice = input.nextInt();
        switch (choice){
            case 1:
                //用户注册
                regist();
                break;
            case 2:
                //用户登录
                login();
                break;
        }
    }

    private static void regist() throws Exception{
        //1创建
        Socket socket = new Socket("192.168.0.101", 6666);
        //2获取输入输出流
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"));
        //3获取信息
        String json = getRegistInfo();
        //4发送信息
        bw.write(json);
        //换行
        bw.newLine();
        //刷新数据到存储
        bw.flush();
        //5接收
        String reply = br.readLine();
        System.out.println("服务器回复了："+reply);
        //6关闭
        bw.close();
        br.close();
        socket.close();
    }

    private static String getRegistInfo() {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入用户编号：");
        int id = input.nextInt();
        System.out.println("请输入姓名：");
        String name = input.next();
        System.out.println("请输入密码：");
        String pwd = input.next();
        System.out.println("请输入年龄：");
        int age = input.nextInt();
        String json = "{id:"+id+",name:"+name+",pwd:"+pwd+",age:"+age+"}";
        return json;
    }

    private static String getLoginInfo() {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入用户编号：");
        int id = input.nextInt();
        System.out.println("请输入密码：");
        String pwd = input.next();
        String json = "{id:"+id+",pwd:"+pwd+"}";
        return json;
    }

    private static void login() throws Exception{
        //1创建
        Socket socket = new Socket("192.168.0.101", 6688);
        //2获取输入输出流
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"));
        //3获取信息
        String json = getLoginInfo();
        //4发送信息
        bw.write(json);
        //换行
        bw.newLine();
        //刷新数据到存储
        bw.flush();
        //5接收
        String reply = br.readLine();
        System.out.println("服务器回复了："+reply);
        //6关闭
        bw.close();
        br.close();
        socket.close();
    }
}
